package com.luck.easyfoodbatch.ui;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.adapter.OrderAdapter;
import com.luck.easyfoodbatch.dialog.CustomDialog;
import com.luck.easyfoodbatch.entity.OrderM;
import com.luck.easyfoodbatch.mvp.model.Collect;
import com.luck.easyfoodbatch.mvp.model.MyAddress;
import com.luck.easyfoodbatch.mvp.model.MyOrdersM;
import com.luck.easyfoodbatch.mvp.order.CancelOrderModel;
import com.luck.easyfoodbatch.mvp.order.CancelOrderPresenter;
import com.luck.easyfoodbatch.mvp.order.CancelOrderView;
import com.luck.easyfoodbatch.mvp.order.ConfirmOrderModel;
import com.luck.easyfoodbatch.mvp.order.ConfirmOrderPresenter;
import com.luck.easyfoodbatch.mvp.order.ConfirmOrderView;
import com.luck.easyfoodbatch.mvp.order.DeleteOrderModel;
import com.luck.easyfoodbatch.mvp.order.DeleteOrderPresenter;
import com.luck.easyfoodbatch.mvp.order.DeleteOrderView;
import com.luck.easyfoodbatch.mvp.order.MyOrdersModel;
import com.luck.easyfoodbatch.mvp.order.MyOrdersPresenter;
import com.luck.easyfoodbatch.mvp.order.MyOrdersView;
import com.luck.easyfoodbatch.mvp.order.OrderPayModel;
import com.luck.easyfoodbatch.mvp.order.OrderPayPresenter;
import com.luck.easyfoodbatch.mvp.order.OrderPayView;
import com.luck.easyfoodbatch.pay.PayResult;
import com.luck.easyfoodbatch.simcpux.Constants;
import com.luck.easyfoodbatch.util.AlipayUtil;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;
import com.luck.easyfoodbatch.util.Utils;
import com.luck.easyrecyclerview.EasyRecyclerView;
import com.luck.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.luck.easyrecyclerview.decoration.RecycleViewDivider;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MyOrderActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener, OrderPayView, SwipeRefreshLayout.OnRefreshListener, RecyclerArrayAdapter.OnLoadMoreListener, MyOrdersView, DeleteOrderView, CancelOrderView, ConfirmOrderView {
    @BindView(R.id.rb_tab1)
    RadioButton rbTab1;
    @BindView(R.id.rb_tab2)
    RadioButton rbTab2;
    @BindView(R.id.rb_tab3)
    RadioButton rbTab3;
    @BindView(R.id.rb_tab4)
    RadioButton rbTab4;
    @BindView(R.id.rb_tab5)
    RadioButton rbTab5;
    @BindView(R.id.rabs)
    RadioGroup rabs;
    @BindView(R.id.indicator)
    View indicator;
    @BindView(R.id.recyclerView)
    EasyRecyclerView recyclerView;
    private int type = 0;
    private List<MyOrdersM.DataBean.ModelsBean> list = new ArrayList<>();
    private HashMap<String, List<MyOrdersM.DataBean.ModelsBean>> dataMap = new HashMap<>();
    private OrderAdapter adapter;
    private MyOrdersModel ordersModel;
    private String status = "";
    private int totalPage = 1;
    private int page = 1;
    private int pay_type = 1;
    private IWXAPI api;
    private boolean isRefresh = false;
    private DeleteOrderModel deleteOrderModel;
    private CancelOrderModel cancelOrderModel;
    private ConfirmOrderModel confirmOrderModel;
    private static final int SDK_PAY_FLAG = 1;
    private OrderPayModel orderPayModel;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("action.app.refresh.evaluate")) {
                page = 1;
                isRefresh = true;
                ordersModel.requestMyOrdersList(page, status);
            }
        }
    };


    private Handler MyHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        isRefresh = true;
                        page = 1;
                        ordersModel.requestMyOrdersList(page, status);
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(mContext, "支付结果确认中",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(mContext, "支付失败",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_order, "我的订单", MODE_BACK_NAVIGATION);
        ButterKnife.bind(this);
        api = WXAPIFactory.createWXAPI(this, null);
        api.registerApp(Constants.APP_ID);
        registerReceiver(receiver, "action.app.refresh.evaluate");
        type = getIntent().getIntExtra("type", 0);
        status = getIntent().getStringExtra("status");
        rabs.setOnCheckedChangeListener(this);
        switch (type) {
            case 1:
                rabs.post(new Runnable() {
                    @Override
                    public void run() {
                        rbTab2.setChecked(true);
                        initCheckedTab(rbTab2);
                    }
                });
                break;
            case 2:
                rabs.post(new Runnable() {
                    @Override
                    public void run() {
                        rbTab3.setChecked(true);
                        initCheckedTab(rbTab3);
                    }
                });
                break;
            case 3:
                rabs.post(new Runnable() {
                    @Override
                    public void run() {
                        rbTab4.setChecked(true);
                        initCheckedTab(rbTab4);
                    }
                });
                break;
            case 4:
                rabs.post(new Runnable() {
                    @Override
                    public void run() {
                        rbTab5.setChecked(true);
                        initCheckedTab(rbTab5);
                    }
                });
                break;
            default:
                rabs.post(new Runnable() {
                    @Override
                    public void run() {
                        initCheckedTab(rbTab1);
                        showProgressDialog(getString(R.string.app_loading));
                        ordersModel.requestMyOrdersList(page, status);
                    }
                });
                break;
        }

        ordersModel = new MyOrdersPresenter(this, mContext);
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new RecycleViewDivider(
                mContext, LinearLayoutManager.HORIZONTAL, Utils.dip2px(mContext, 0), getResources().getColor(R.color.transparent)));
        recyclerView.setLayoutManager(manager);
        adapter = new OrderAdapter(mContext, operationOrder);
        recyclerView.setAdapterWithProgress(adapter);
        adapter.setMore(R.layout.view_more, this);
        adapter.setNoMore(R.layout.view_nomore);
        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (isFastDoubleClick()) {
                    return;
                }
                try {
                    MyOrdersM.DataBean.ModelsBean modelsBean = list.get(position);
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putString("order_id", modelsBean.getOrder_id() + "");
                    bundle.putSerializable("item", (Serializable) modelsBean.getOrderInfo());
                    intent.setClass(mContext, OrderDetailsActivity.class);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 200);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        adapter.addAll(list);
        recyclerView.setAdapter(adapter);
        recyclerView.setRefreshListener(this);
    }

    /**
     * 操作订单
     */
    public OrderAdapter.OnOperationOrder operationOrder = new OrderAdapter.OnOperationOrder() {
        @Override
        public void onOperationDelete(int type, MyOrdersM.DataBean.ModelsBean bean) {
            Bundle bundle = new Bundle();
            switch (type) {
                case 1:
                    // 删除订单
                    showOrderDialog(1, bean.getOrder_id() + "");
                    deleteOrderModel = new DeleteOrderPresenter(MyOrderActivity.this, mContext);
                    break;
                case 2:
                    // 取消订单
                    showOrderDialog(2, bean.getOrder_id() + "");
                    cancelOrderModel = new CancelOrderPresenter(MyOrderActivity.this, mContext);
                    break;
                case 3:
                    // 确认收货
                    showOrderDialog(3, bean.getOrder_id() + "");
                    confirmOrderModel = new ConfirmOrderPresenter(MyOrderActivity.this, mContext);
                    break;
                case 4:
                    // 去评价
                    List<MyOrdersM.DataBean.ModelsBean.OrderInfoBean> orderInfo = bean.getOrderInfo();
                    bundle.putString("order_id", bean.getOrder_id() + "");
                    bundle.putString("shop_name", bean.getShop_name() + "");
                    bundle.putString("shop_avatar", bean.getShop_avatar());
                    bundle.putSerializable("orderInfo", (Serializable) orderInfo);
                    startAct(CommentActivity.class, bundle);
                    break;
                case 5:
                    // 查看物流
                    bundle.putString("postid", bean.getPost_sn());
                    bundle.putString("use_ydx", bean.getUse_ydx());
                    Tools.copy(bean.getPost_sn(), MyOrderActivity.this);
                    startAct(LogisticsActivity.class, bundle);
                    break;
                case 6:
                    // 去付款
                    String order_id = bean.getOrder_id() + "";
                    showApplyDialog(order_id);
                    break;
            }
        }
    };

    /**
     * 支付方式
     */
    protected void showApplyDialog(final String order_id) {
        final CustomDialog dialog = new CustomDialog(mContext, LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT, R.layout.wind_apply_dialog_xml, R.style.Theme_dialog);
        ImageView iv_alipy = (ImageView) dialog.findViewById(R.id.iv_alipy);
        ImageView iv_wechat = (ImageView) dialog.findViewById(R.id.iv_wechat);
        Button btn_commit = (Button) dialog.findViewById(R.id.btn_commit);
        orderPayModel = new OrderPayPresenter(MyOrderActivity.this, mContext);
        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        iv_alipy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_type = 1;
                orderPayModel.requestOrderPay(order_id, pay_type + "");
                dialog.dismiss();
            }
        });
        iv_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_type = 2;
                orderPayModel.requestOrderPay(order_id, pay_type + "");
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    /**
     * 操作订单
     */
    private void showOrderDialog(final int type, final String orderId) {
        final CustomDialog dialog = new CustomDialog(mContext, App.screenWidth * 3 / 4,
                App.screenHeight / 4, R.layout.wind_base_dialog_xml, R.style.Theme_dialog);
        Button btn_cancel = (Button) dialog.findViewById(R.id.btn_cancel);
        Button btn_commit = (Button) dialog.findViewById(R.id.btn_commit);
        final TextView tv_content = (TextView) dialog.findViewById(R.id.tv_content);
        switch (type) {
            case 1:
                tv_content.setText("确定要删除该订单吗？");
                break;
            case 2:
                tv_content.setText("确定要取消该订单吗？");
                break;
            case 3:
                tv_content.setText("请先确认订单无误，在收货。");
                break;
        }

        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        btn_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showProgressDialog(getString(R.string.app_loading));
                switch (type) {
                    case 1:
                        deleteOrderModel.requestDeleteOrder(0, orderId);
                        break;
                    case 2:
                        cancelOrderModel.requestCancelOrder(orderId);
                        break;
                    case 3:
                        confirmOrderModel.requestConfirmOrder(orderId);
                        break;
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /**
     * 选中tab页
     */
    private void initCheckedTab(final RadioButton rbTab) {
        rabs.post(new Runnable() {
            @Override
            public void run() {
                buildIndicatorAnimatorTowards(rbTab).start();
            }
        });
    }

    /**
     * 指示器动画
     *
     * @param tab
     * @return
     */
    private AnimatorSet buildIndicatorAnimatorTowards(TextView tab) {
        ObjectAnimator xAnimator = ObjectAnimator.ofFloat(indicator, "X", indicator.getX(), tab.getX());

        final ViewGroup.LayoutParams params = indicator.getLayoutParams();
        ValueAnimator widthAnimator = ValueAnimator.ofInt(params.width, tab.getMeasuredWidth());
        widthAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                params.width = (Integer) animation.getAnimatedValue();
                indicator.setLayoutParams(params);
            }
        });

        AnimatorSet set = new AnimatorSet();
        set.setInterpolator(new FastOutSlowInInterpolator());
        set.playTogether(xAnimator, widthAnimator);

        return set;
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i) {
            case R.id.rb_tab1:
                status = "";
                buildIndicatorAnimatorTowards(rbTab1).start();
                break;
            case R.id.rb_tab2:
                status = "0";
                buildIndicatorAnimatorTowards(rbTab2).start();
                break;
            case R.id.rb_tab3:
                status = "1";
                buildIndicatorAnimatorTowards(rbTab3).start();
                break;
            case R.id.rb_tab4:
                status = "2";
                buildIndicatorAnimatorTowards(rbTab4).start();
                break;
            case R.id.rb_tab5:
                status = "3";
                buildIndicatorAnimatorTowards(rbTab5).start();
                break;
        }

        list = dataMap.get(status);// 根据状态取相应的数据
        if (list != null && list.size() > 0) {
            adapter.clear();
            adapter.addAll(list);
            adapter.notifyDataSetChanged();
        } else {
            list = new ArrayList<>();
            showProgressDialog(getString(R.string.app_loading));
            page = 1;
            isRefresh = true;
            ordersModel.requestMyOrdersList(page, status);
        }
    }

    @Override
    public void onLoadMore() {
        //刷新
        page++;
        if (!isNetworkConnected()) {
            adapter.pauseMore();
            return;
        }
        if (page > totalPage) {
            adapter.stopMore();
            return;
        }
        ordersModel.requestMyOrdersList(page, status);
    }

    @Override
    public void onRefresh() {
        isRefresh = true;
        page = 1;
        ordersModel.requestMyOrdersList(page, status);
    }

    @Override
    public void myOrdersListSuccess(MyOrdersM model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                totalPage = model.getData().getTotalPage();
                if (isRefresh) {
                    list.clear();
                    isRefresh = false;
                }

                list.addAll(model.getData().getModels());
                if (list == null) {
                    list = new ArrayList<>();
                }
                dataMap.put(status, list);// 保存请求记录
                adapter.clear();
                adapter.addAll(list);
                adapter.notifyDataSetChanged();
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void deleteOrderSuccess(Collect model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                isRefresh = true;
                page = 1;
                ordersModel.requestMyOrdersList(page, status);
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void cancelOrderSuccess(Collect model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                isRefresh = true;
                page = 1;
                ordersModel.requestMyOrdersList(page, status);
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void confirmOrderSuccess(Collect model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                isRefresh = true;
                page = 1;
                ordersModel.requestMyOrdersList(page, status);
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    @Override
    public void httpStatusError() {
    }

    @Override
    public void hideLoading() {
        hideShowProgress();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 200:
                    isRefresh = true;
                    page = 1;
                    ordersModel.requestMyOrdersList(page, status);
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

    @Override
    public void orderPaySuccess(OrderM model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                OrderM.DataBean bean = model.getData();
                String params = bean.getParams();
                switch (pay_type) {
                    case 1:
                        new AlipayUtil(MyOrderActivity.this, params, MyHandler);
                        break;
                    case 2:
                        wechatApply(bean);
                        break;
                }
            }
        }
    }

    /**
     * 微信支付
     *
     * @param bean
     */
    private void wechatApply(OrderM.DataBean bean) {
        try {
            PayReq req = new PayReq();
            req.appId = bean.getAppid();
            req.partnerId = bean.getPartnerid();
            req.prepayId = bean.getPrepayid();
            req.nonceStr = bean.getNoncestr();
            req.timeStamp = bean.getTimestamp() + "";
            req.packageValue = bean.getPackageX();
            req.sign = bean.getSign();
            Toast.makeText(this, "正在发起微信支付，请稍候...", Toast.LENGTH_SHORT).show();
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            api.registerApp(Constants.APP_ID);
            api.sendReq(req);
        } catch (Exception e) {
            Log.e("PAY_GET", "异常：" + e.getMessage());
        }
    }

}
